<template>
  <div class="rework_work_stage_edit">
    <one-title title="编辑工艺-处理任务" @refreshData="init">
      <div class="mes_btn">
        <el-button @click="returnPage">
          <i class="iconfont icon-btn_return"></i>
          返回列表
        </el-button>
        <el-button @click="save(false)" type="primary" v-if="!isEmpty&&!isLoading">
          <i class="iconfont icon-btn_Save"></i>
          保存工艺
        </el-button>
        <el-button @click="handleSubmit" type="success" v-if="!isEmpty&&!isLoading">
          <i class="iconfont icon-btn_Save"></i>
          任务提交
        </el-button>
      </div>
    </one-title>
    <div class="fixed_top_56">
      <empty-page v-if="isEmpty&&!isLoading"></empty-page>
      <div v-loading="isLoading" v-if="!isEmpty">
        <process
          :infoData="processDetail">
        </process>
        <work-stage-edit
          ref="workStageEdit"
          :materialName="processDetail.materialName || ''"
          :entry="'batch'"
          :workstageData="workstageData"
          @tempSave="init"
          @change="handleChange"
          @saveStage="handleSaveStage"
        >
          <div class="get_old">
            <div class="get_old_btn">
              <div class="mes_btn">
                <el-button
                  size="small"
                  type="primary"
                  plain
                  @click="handleClick"
                >
                  <i class="iconfont icon-btn_addnew"></i>
                  <span>获取原工艺路线</span>
                </el-button>
              </div>
            </div>
          </div>
        </work-stage-edit>
      </div>
    </div>
  </div>
</template>

<script>
import EmptyPage from '@/components/EmptyPage'

// 工艺详情
import {Process} from '../../../../components/process'
import {WorkStageEdit} from '../../../../components/workStageEdit'
import checkAssignRule from '../../../../validate/checkAssignRule'

// 获取工艺详情接口
let getTechProcInterface = 'a/tmpturnoverbatch/tmpTurnoverBatch/getTechProc'
// 获取原工艺路线接口
let getOriginalWorkstageInterface = 'a/tmpturnoverbatch/tmpTurnoverBatch/getOriginalWorkstage'
// 获取现工艺路线接口
let getNowWorkstageInterface = 'a/batchworkstage/batchWorkstage/list'
// 保存工艺路线接口
let saveTechProcInterface = 'a/tmpturnoverbatch/tmpTurnoverBatch/saveTechProc'

// store模块
let storeModule = 'temporaryWorkbench'

export default {
  name: 'ReworkWorkStageEdit',
  components: {
    EmptyPage,
    Process,
    WorkStageEdit
  },
  data() {
    return {
      isLoading: false,
      isEmpty: false,
      startWatch: false,
    }
  },
  computed: {
    saveState() {
      return this.$store.state.saveState
    },
    // 可选工序
    workstageData() {
      return this.$store.state[storeModule].workstageData.list || []
    },
    // 工艺详情
    processDetail() {
      return this.$store.state[storeModule].reworkProcessDetail
    },
    // 工序列表
    stageList() {
      return this.$store.state[storeModule].nowWorkstage.list || []
    },
    // 原工序列表
    originalWorkstage() {
      return this.$store.state[storeModule].originalWorkstage || []
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.startWatch = false
      this.isLoading = true
      Promise.all([this.getProcessDetail(), this.getNowWorkStage(), this.getWorkStageList()])
        .finally(() => {
          this.isLoading = false
        })
    },
    getProcessDetail() {
      let postData = {
        method: 'post',
        url: getTechProcInterface,
        data: {
          // 列表项的id
          // turnoverId: '1',
          turnoverId: this.$route.query.id
        },
        module: storeModule,
        state: 'reworkProcessDetail',
      }
      return this.$store.dispatch('saveData', postData)
        .then((value) => {
          if (Object.keys(value).length === 0) this.isEmpty = true
        })
        .catch(() => {
          this.isEmpty = true
        })
    },
    // 获取当前工艺路线，获取完当前工艺路线后开始监听是否编辑
    getNowWorkStage() {
      let postData = {
        method: 'post',
        url: getNowWorkstageInterface,
        data: {
          pageSize: 1000,
          pageNo: 1,
          query: {
            // 列表中的turnoverId
            turnoverBatchId: this.$route.query.turnoverId,
          },
          sort: {
            sort: 'asc'
          }
        },
        module: storeModule,
        state: 'nowWorkstage',
      }
      return this.$store.dispatch('saveData', postData)
        .then((value) => {
          this.startWatch = true
          if (Object.keys(value).length === 0) this.isEmpty = true
          this.$refs.workStageEdit.initStageList(this.stageList)
        })
        .catch(() => {
          this.isEmpty = true
        })
    },
    // 获取原工艺路线
    getOriginalWorkstage() {
      let postData = {
        method: 'post',
        url: getOriginalWorkstageInterface,
        data: {
          // 列表项的id
          // turnoverId: '1',
          turnoverId: this.$route.query.id
        },
        module: storeModule,
        state: 'originalWorkstage',
      }
      return this.$store.dispatch('saveData', postData)
        .then(() => {
          this.$store.commit('SortReworkWorkStageList', this.originalWorkstage)
          this.$refs.workStageEdit.initStageList(this.stageList)
        })
    },
    // 工序序号补0操作
    handleChange(value) {
      value.map((item, index) => {
        let sort = index + 1
        item.sort = sort < 10 ? ('0' + sort) : sort
      })
      this.$store.commit('SortReworkWorkStageList', value)
    },
    handleClick() {
      if (this.stageList.length !== 0) {
        this.confirmOpen('该操作将覆盖已编辑工艺路线, 是否继续?', '获取提示')
          .then(() => {
            this.getOriginalWorkstage()
          })
      } else {
        this.getOriginalWorkstage()
      }
    },
    // 返回列表
    returnPage() {
      this.$router.push('/temporaryWorkbench')
    },
    handleSaveStage() {
      this.save().then(() => {
        this.$refs.workStageEdit.hasStageChange = false
      })
    },
    /**
     * 保存工艺,不跳转
     * @param beforeSubmit 是否是提交前
     * @returns {Promise<any | never>}
     */
    save(beforeSubmit = false) {
      if (this.saveState === true) return
      if (!checkAssignRule(this.stageList)) return
      let commitObj = {
        method: 'post',
        url: saveTechProcInterface,
        data: {
          // turnoverId: '1',
          turnoverId: this.$route.query.id,
          batchWorkstageList: this.stageList
        },
        noCommit: true
      }
      this.$store.commit('SetSaveState', true)
      return this.$store.dispatch('saveData', commitObj)
        .then(() => {
          this.startWatch = false
          if (!beforeSubmit) {
            this.saveSuccess()
          }
        })
        .catch(() => {
          this.$store.commit('SetSaveState', false)
        })
    },
    saveSuccess() {
      this.$store.commit('SetHasDetailChange', false)
      this.$message.success({
        message: '保存成功',
        duration: 1500,
        center: true,
        onClose: () => {
          this.getNowWorkStage()
            .then(() => {
              this.$store.commit('SetSaveState', false)
            })
        }
      })
    },
    // 任务提交，跳转
    handleSubmit() {
      this.save(true).then(() => {
        let commitObj = {
          method: 'post',
          url: 'a/tmpturnoverbatch/tmpTurnoverBatch/submitTask',
          data: {
            tmpBatchIds: [this.$route.query.id],
          },
          noCommit: true
        }
        this.$store.dispatch('saveData', commitObj)
          .then(() => {
            this.$message.success({
              message: '保存成功',
              duration: 1500,
              center: true,
              onClose: () => {
                this.$store.commit('SetHasDetailChange', false) // 保存成功时需要将页面变化标记重置回false
                this.$store.dispatch('delCurrentViews', this.$route)
                  .then(() => {
                    this.$store.commit('SetSaveState', false)
                    this.$router.push('/temporaryWorkbench')
                    this.$store.commit('SetRefresh', true)
                  })
              }
            })
          })
          .catch(() => {
            this.$store.commit('SetSaveState', false)
          })
      })
    },
    // 获取可选工序列表
    getWorkStageList() {
      let commitObj = {
        method: 'post',
        url: 'a/workstagerepository/workstageRepository/list',
        module: storeModule,
        state: 'workstageData',
        data: {
          'pageSize': 10000,
          'pageNo': 1
        }
      }
      return this.$store.dispatch('saveData', commitObj)
    },
  },
  watch: {
    stageList: {
      handler() {
        if (this.startWatch) {
          this.$store.commit('SetHasDetailChange', true)
        } else {
          this.$store.commit('SetHasDetailChange', false)
        }
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
  .rework_work_stage_edit {
    .get_old {
      text-align: right;
      .get_old_btn {
        display: inline-block;
        margin-right: 20px;
        margin-top: 20px;
      }
    }
  }
</style>
